package fr.pud.client.controller;

import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.File;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFileChooser;
import javax.swing.KeyStroke;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.openstreetmap.gui.jmapviewer.DefaultMapController;

import fr.pud.client.i18n.LanguagesConstants;
import fr.pud.client.images.ImagesDatabase;
import fr.pud.client.view.SWReadingXML;

/**
 * The action for opening an existing result file (format XML) and print it on
 * the map
 * Apr 9, 2012 - OSE.
 * @author Simon Devineau, Adrien Hierry, Leopold Houdin, Pierre Reliquet
 *         Ecole des Mines de Nantes
 *         OpenResultFile.java
 */
public class OpenResultFile extends AbstractAction {
    /**
     * The serial UID
     */
    private static final long serialVersionUID = -3395275705171781525L;

    /**
     * Sets the controller up name, logo...
     */
    public OpenResultFile() {
        this.putValue(Action.NAME, LanguagesConstants.LANGUAGE
                .getObject(LanguagesConstants.PRINT_EXISTING_XML));
        this.putValue(Action.SHORT_DESCRIPTION, LanguagesConstants.LANGUAGE
                .getObject(LanguagesConstants.PRINT_EXISTING_XML_DESCRIPTION));
        this.putValue(SMALL_ICON, ImagesDatabase.EXISTING_FILES);
        if (DefaultMapController.isPlatformOsx()) {
            this.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(
                    KeyEvent.VK_O, InputEvent.META_DOWN_MASK));
        }
        else {
            this.putValue(Action.ACCELERATOR_KEY,
                    KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK));
        }
    }

    /**
     * Load a result file by opening a JFileChooser, there is a filter to ensure
     * that an xml file is selected.
     */
    @Override
    public void actionPerformed(ActionEvent arg0) {
        /*
         * Initialization of the explorer
         */
        JFileChooser explorer;
        File f = new File("");
        explorer = new JFileChooser(f.getAbsolutePath());
        explorer.setFileSelectionMode(JFileChooser.FILES_ONLY);
        FileFilter xmlRestriction = new FileNameExtensionFilter(
                LanguagesConstants.LANGUAGE.getString(LanguagesConstants.FILE)
                        + " xml", "xml");
        explorer.setFileFilter(xmlRestriction);
        /*
         * Getting the file
         */
        explorer.showOpenDialog(null);
        if (explorer.getSelectedFile() != null) {
            SWReadingXML read = new SWReadingXML(explorer.getSelectedFile()
                    .getAbsolutePath());
            read.execute();
        }
    }
}
